package com.gitee.feizns.web.dao.handler.meta;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.enums.FieldFill;
import com.gitee.feizns.bean.Property;
import com.gitee.feizns.bean.PropertyUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;

/**
 * @author feizns
 * @since 2019/7/26
 */
public abstract class AbstractGeneralFillInputHandler implements FillInputHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        handler(metaObject.getOriginalObject(), this::insertFill);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        handler(metaObject.getOriginalObject(), this::updateFill);
    }

    private void handler(Object original, Predicate<TableField> predicate) {
        Object et = Map.class.isAssignableFrom(original.getClass()) ? ((Map) original).get("et") : original;
        PropertyUtils.rwProps(et).forEach(prop -> {
            TableField field = prop.getAnnotation(TableField.class);
            if ( field != null ) {
                if ( predicate.test(field) )
                    handle(prop, et);
            }
        });
    }

    /**
     * 处理过程
     * @param prop
     */
    protected abstract void handle(Property<Object, Object> prop, Object original);

    private boolean insertFill(TableField field) {
        return (field.fill() == FieldFill.INSERT || field.fill() == FieldFill.INSERT_UPDATE);
    }

    private boolean updateFill(TableField field) {
        return field.fill() == FieldFill.UPDATE || field.fill() == FieldFill.INSERT_UPDATE;
    }

}
